package com.ruyuan.authenticate;

import com.ruyuan.token.TokenUtil;
import com.ruyuan.util.ApplicationContextUtil;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.pam.ModularRealmAuthenticator;
import org.apache.shiro.realm.Realm;
import org.springframework.context.ApplicationContext;

import java.util.Collection;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author xx
 */
public class MyModularRealmAuthenticator extends ModularRealmAuthenticator {

    public MyModularRealmAuthenticator() {
        this.setAuthenticationStrategy(new OnlyOneAuthenticationStrategy());
    }

    @Override
    protected AuthenticationInfo doAuthenticate(AuthenticationToken authenticationToken) throws AuthenticationException {
        assertRealmsConfigured();
        Collection<Realm> realms = getRealms();
        TokenUtil tokenUtil = ApplicationContextUtil.getApplicationContext().getBean(TokenUtil.class);
        List<Realm> filterRealms = realms.stream().filter(it -> tokenUtil.supports(authenticationToken, it)).collect(Collectors.toList());
        if (filterRealms.size() == 1) {
            return doSingleRealmAuthentication(filterRealms.iterator().next(), authenticationToken);
        } else {
            return doMultiRealmAuthentication(filterRealms, authenticationToken);
        }
    }
}
